package com.blic.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blic.vo.AccessToken;
import com.blic.vo.UserInfo;
 

/**
 * 公众平台通用接口工具类
 * 
 * @author lzw
 * @date 2013-08-09
 */

@Component
public class OAuthUtil {
	private static Logger log = LoggerFactory.getLogger("WX-OAUTH-LOG");

	// 获取access_token的接口地址（GET） 限200（次/天）
	private final static String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	private final static String access_userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	private final static String access_userinfo_web_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	@Value("${appID}")
	private String appId ;
	
	@Value("${appsecret}")
	private String  secretId;
	/**
	 * 网页基本授权获取token信息
	 * 
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 */
	public static AccessToken getAccessToken(String appid, String appsecret,
			String code, String state, String authorization_code) {
		AccessToken accessToken = null;

		String requestUrl = access_token_url.replace("APPID", appid)
				.replace("SECRET", appsecret).replace("CODE", code)
				.replace("authorization_code", authorization_code);

		JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null,
				1);
		// System.out.println(".....jsonObject=" + jsonObject);
		// System.out.println(".....jsonObject=" + jsonObject.toString());
		// 如果请求成功
		log.info("getAccessToken|" + requestUrl + "|"
				+ JSON.toJSONString(requestUrl));
		if (null != jsonObject) {
			try {
				if (jsonObject.containsKey("openid")) {
					accessToken = new AccessToken();
					accessToken.setToken(jsonObject.getString("access_token"));
					accessToken.setExpiresIn(jsonObject
							.getInteger("expires_in"));
					accessToken.setRefresh_token(jsonObject
							.getString("refresh_token"));
					accessToken.setOpenid(jsonObject.getString("openid"));
					accessToken.setScope(jsonObject.getString("scope"));
					log.info("OAuthUtil  getAccessToken  accessToken="
							+ JSONObject.toJSONString(accessToken).toString());
				} else {
					log.error("获取token失败 errcode:{} errmsg:{}",
							jsonObject.getInteger("errcode"),
							jsonObject.getString("errmsg"));
					return null;
				}

			} catch (Exception e) {
				accessToken = null;
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}",
						jsonObject.getInteger("errcode"),
						jsonObject.getString("errmsg"));
				e.printStackTrace();
			}
		}
		return accessToken;
	}

	/**
	 * 网页基本授权获取token信息
	 * 
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 */
	private static AccessToken getAccessToken2(String appid, String appsecret,
			String code, String state, String authorization_code) {
		AccessToken accessToken = new AccessToken();

		String requestUrl = access_token_url.replace("APPID", appid)
				.replace("SECRET", appsecret).replace("CODE", code)
				.replace("authorization_code", authorization_code);

		JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null,
				1);
		// System.out.println(".....jsonObject=" + jsonObject);
		// System.out.println(".....jsonObject=" + jsonObject.toString());
		// 如果请求成功
		log.info("getAccessToken|" + requestUrl + "|"
				+ JSON.toJSONString(requestUrl));
		if (null != jsonObject) {
			try {
				if (jsonObject.containsKey("openid")) {
					accessToken.setToken(jsonObject.getString("access_token"));
					accessToken.setExpiresIn(jsonObject
							.getInteger("expires_in"));
					accessToken.setRefresh_token(jsonObject
							.getString("refresh_token"));
					accessToken.setOpenid(jsonObject.getString("openid"));
					accessToken.setScope(jsonObject.getString("scope"));
					log.info("OAuthUtil  getAccessToken  accessToken="
							+ JSONObject.toJSONString(accessToken).toString());
				} else {
					log.error("获取token失败 errcode:{} errmsg:{}",
							jsonObject.getInteger("errcode"),
							jsonObject.getString("errmsg"));
					accessToken.setErrcode(jsonObject.getInteger("errcode"));
					accessToken.setErrmsg(jsonObject.getString("errmsg"));
					return accessToken;
				}

			} catch (Exception e) {
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}",
						jsonObject.getInteger("errcode"),
						jsonObject.getString("errmsg"));
				accessToken.setErrcode(jsonObject.getInteger("errcode"));
				accessToken.setErrmsg(jsonObject.getString("errmsg"));
				return accessToken;
			}
		}
		return accessToken;
	}

	/**
	 * 
	 * @Title: getUserinfo
	 * @Description: 通过网页授权token与openid获取用户基本信息
	 * @param @param access_token
	 * @param @param openid
	 * @param @return 设定文件
	 * @return UserInfo 返回类型
	 * @throws
	 */
	public static UserInfo getUserinfo(String access_token, String openid) {
		UserInfo userInfo = null;
		access_token = access_token!=null?access_token:"null";
		String requestUrl = access_userinfo_url.replace("ACCESS_TOKEN",
				access_token).replace("OPENID", openid);
		log.info("获取用户信息进行校验：access_token=" + access_token + ",openid="
				+ openid);
		JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null,
				1);
		// 如果请求成功
		if (null != jsonObject && jsonObject.containsKey("subscribe")) {
			try {
				userInfo = new UserInfo();
				userInfo.setSubscribe(jsonObject.getString("subscribe"));
				if ("1".equals(userInfo.getSubscribe())) {
					userInfo.setOpenid(jsonObject.getString("openid"));
					userInfo.setCity(jsonObject.getString("city"));
					userInfo.setCountry(jsonObject.getString("country"));
					userInfo.setHeadimgurl(jsonObject.getString("headimgurl"));
					userInfo.setNickname(jsonObject.getString("nickname"));
					userInfo.setProvince(jsonObject.getString("province"));
					userInfo.setSex(jsonObject.getString("sex"));
				}
			} catch (Exception e) {
				userInfo = new UserInfo();
				userInfo.setErrcode(jsonObject.getInteger("errcode"));
				userInfo.setErrmsg(jsonObject.getString("errmsg"));
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}",
						jsonObject.getInteger("errcode"),
						jsonObject.getString("errmsg"));
			}
		} else {
			try {
				userInfo = new UserInfo();
				userInfo.setErrcode(jsonObject.getInteger("errcode"));
				userInfo.setErrmsg(jsonObject.getString("errmsg"));
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}",
						jsonObject.getInteger("errcode"),
						jsonObject.getString("errmsg"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return userInfo;
	}

	/**
	 * 通过code获取用户基本信息
	 * 
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 *//*
	public static UserInfo getUserinfomation(String code) {
		UserInfo userInfo = new UserInfo();
		String state = "1";
		String authorization_code = "authorization_code";
		AccessToken accessToken = OAuthUtil.getAccessToken2(WXconstant.APPID,
				WXconstant.APPSECRET, code, state, authorization_code);
		userInfo.setErrcode(accessToken.getErrcode());
		if (0 == accessToken.getErrcode()) {
			String requestUrl = access_userinfo_web_url.replace("ACCESS_TOKEN",
					accessToken.getToken()).replace("OPENID",
					accessToken.getOpenid());
			JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET",
					null, 1);
			// 如果请求成功
			if (null != jsonObject && jsonObject.containsKey("openid")) {
				try {
					userInfo.setOpenid(jsonObject.getString("openid"));
					userInfo.setCity(jsonObject.getString("city"));
					userInfo.setCountry(jsonObject.getString("country"));
					userInfo.setHeadimgurl(jsonObject.getString("headimgurl"));
					userInfo.setNickname(jsonObject.getString("nickname"));
					userInfo.setProvince(jsonObject.getString("province"));
					userInfo.setSex(jsonObject.getString("sex"));
				} catch (Exception e) {
					userInfo.setErrcode(jsonObject.getInteger("errcode"));
					userInfo.setErrmsg(jsonObject.getString("errmsg"));
					// 获取token失败
					log.error("获取token失败 errcode:{} errmsg:{}",
							jsonObject.getInteger("errcode"),
							jsonObject.getString("errmsg"));
					e.printStackTrace();
				}
			}
		}
		log.info("getUserinfomation}userInfo|" + JSON.toJSONString(userInfo));
		return userInfo;
	}
*/
	/**
	 * 
	 * @Title: getOpenId
	 * @Description: 通过code获取用户openid
	 * @param @param code
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	public   String getOpenId(String code) {
		String state = "1";
		String authorization_code = "authorization_code";
		log.info("OAuthUtil  getOpenId  param  code=" + code + ",state="
				+ state + ",authorization_code=" + authorization_code);
		AccessToken accessToken = OAuthUtil.getAccessToken(appId,
				secretId, code, state, authorization_code);
		if (null != accessToken) {
			log.info(JSONObject.toJSONString(accessToken).toString());
			return accessToken.getOpenid();
		} else {
			return null;
		}

	}

	public   AccessToken getUserAccessTokenAndOpenId(String code) {
		String state = "1";
		String authorization_code = "authorization_code";
	
		AccessToken accessToken = OAuthUtil.getAccessToken2(appId,
				secretId, code, state, authorization_code);
		
		return accessToken;  
		
	}

}